package com.merck.service.exportLog;

import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.merck.service.export.GenerateExcelImpl;
import com.merck.service.export.SqlStr;
import com.merck.service.export.TitleMap;
import com.merck.service.impl.ImportDataServiceImpl;
import com.merck.utils.DateUtils;
import com.merck.utils.SendMail;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @program: export_flow
 * @description: 生成日志
 * @author: Lucas
 * @create: 2021-04-08 13:56
 **/
public class GenerateLog {
    private Logger log = Logger.getLogger(GenerateLog.class);
    public void exportLog() {

        Properties pros = new Properties();
        InputStream configStream = null;
        Map<String, Map<String, String>> mapTitle;
        Map<String, String> map;
        try {
            ImportDataServiceImpl importData = new ImportDataServiceImpl();
            String dateStr = DateUtils.format(new Date(), "yyyyMMddHHmmss");
            String fileName = "log" + dateStr+".xlsx";
            configStream = GenerateExcelImpl.class.getClassLoader().getResourceAsStream("db.properties");
            pros.load(configStream);
            String bucketName = (String) pros.get("log.bucket");
            String remoteFileName = (String) pros.get("log.remote") + fileName;
            List<File> attachments = new ArrayList<>();
            mapTitle = TitleMap.getLogTitleMap();
            map = new LinkedHashMap<>();
            map.put("sheet1", LogSqlStr.LOG_SQL);
            File file1 = new File(fileName);
            importData.exportDataExcleApp(map, file1, "excle", mapTitle, null);
            GenerateExcelIntoS3(remoteFileName, bucketName, file1);
            //        备份
            String bucketNameBack = (String) pros.get("log.bucket.back");
            String remoteFileNameBack = pros.get("log.remote.back") + fileName;
            GenerateExcelIntoS3(remoteFileNameBack, bucketNameBack, file1);
            attachments.add(file1);
            log.info("导出当天日志成功");
            String currentDateAsString = DateUtils.getCurrentDateAsString();
            SendMail.sendMail(null, null, "导出当天日志任务在 " + currentDateAsString + " 运行结果通知", SqlStr.SUCESS_SEND_CONTENT, attachments);
            file1.delete();

        } catch (IOException e) {
            String currentDateAsString = DateUtils.getCurrentDateAsString();
            SendMail.sendMail(null, null, "导出当天日志任务在 " + currentDateAsString + " 运行结果通知", SqlStr.FAILURE_SEND_CONTENT, null);
            log.error(e.getMessage());

        }finally {
            if (configStream != null) {
                try {
                    configStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }


    }







    private void GenerateExcelIntoS3(String remoteFileName, String bucketName, File file) {
//        File file = new File("temp.xlsx");
//        log.info("开始生成excel表格");
//        String bucketName = (String) pro.get("export.bucket.name");
//        importData.exportDataExcleApp(map, file, "excle", mapTitle, null);

        //S3环境运行代码开始
//        //把生成的Excel上传到S3，上传的路径为上面两个参数定义 ，为 s3://qa-lego-deployment/templates/ + fileName
//        //可以在HUE中查看
        AmazonS3 s3Client = null;
        try {
            s3Client = openS3ClientByEC2();

            PutObjectRequest poRequest = new PutObjectRequest(bucketName, remoteFileName, file).withCannedAcl(CannedAccessControlList.Private);
            s3Client.putObject(poRequest);
            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName, HttpMethod.POST);
            s3Client.generatePresignedUrl(urlRequest);
//            file.delete();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("将文件写入S3出错" + e.getMessage());
        } finally {
            if (s3Client != null) {
                s3Client.shutdown();
            }
        }
    }
    public static AmazonS3 openS3ClientByEC2() {
        AmazonS3 s3Client = null;
        try {
            s3Client = AmazonS3ClientBuilder.defaultClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return s3Client;
    }
}
